'''
Created on Jan 17, 2011

@author: Administrator
'''
import unittest


from mock import patch


from sniffylib.rpc import core, shell
from testutil import *

PASSWORD = 'password'
BAD_PASSWORD = ''

class Test(unittest.TestCase):


    @patch('sniffylib.localise.core.BaseLocationService')
    def setUp(self, LocationService):
        self.loc_svc = LocationService()
        services = dict(location_svc=self.loc_svc)
        self.shell = shell.SniffyShell(PASSWORD, services) 

    def tearDown(self):
        pass


    def testInterpetBadCommand(self):
        try:
            self.shell.interpret(str2cmd(None, "non"))
            self.fail()
        except core.BadCmdException, e:
            self.assertFalse(e.got_auth)
            

    def testInterpretAuthFail(self):
        CMD = 'loc start'
        try:
            self.shell.interpret(str2cmd(None, CMD))
            self.fail()
        except core.BadAuthCmdException, e:
            self.assertFalse(e.got_auth)
        
    def testInterpretAuthOk(self):
        OWN_CMD = 'own %s' % PASSWORD
        CMD = 'loc start'
        user = 'user'
        self.shell.interpret(str2cmd(user, OWN_CMD))
        self.shell.interpret(str2cmd(user, CMD))
        self.loc_svc.start.assert_called_with()
        
    def testInterpretUndefinedExceptionAuth(self):
        OWN_CMD = 'own %s' % PASSWORD
        CMD = 'loc start'
        user = 'user'
        self.loc_svc.start.side_effect = Exception('Boom!')
        self.shell.interpret(str2cmd(user, OWN_CMD))
        try:
            self.shell.interpret(str2cmd(user, CMD))
            self.fail()
        except core.CmdInternalException, e:
            self.assertTrue(e.got_auth)
        self.loc_svc.start.assert_called_with()

    def testInterpretUndefinedExceptionUnauth(self):
        user = 'user'
        OWN_CMD = 'own %s' % BAD_PASSWORD
        try:
            self.shell.interpret(str2cmd(user, OWN_CMD))
            self.fail()
        except core.CmdException, e:
            self.assertFalse(e.got_auth)
        

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()